<template>
  <div class="task-list-page">
    <!-- 顶部操作区：创建任务、批量操作和筛选同一行 -->
    <el-card class="filter-bar-card" shadow="never">
      <div class="filter-bar filter-bar-flex">
        <div class="filter-left">
          <el-input v-model="search.title" placeholder="搜索任务标题" prefix-icon="el-icon-search" class="search-input" @keyup.enter="doSearch" />
          <el-select v-model="search.type" placeholder="任务类型" class="filter-item" style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="日常任务" value="DAILY" />
            <el-option label="限时任务" value="TIME_LIMITED" />
          </el-select>
          <el-select v-model="search.status" placeholder="任务状态" class="filter-item" style="width: 120px">
            <el-option label="全部" value="" />
            <el-option label="待发布" value="PENDING_PUBLISH" />
            <el-option label="已发布" value="PUBLISHED" />
            <el-option label="禁用" value="DISABLED" />
          </el-select>
          <el-date-picker v-model="search.startTime" type="daterange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" class="filter-item" style="width: 240px" />
          <el-button type="primary" @click="doSearch">筛选</el-button>
          <el-button type="default" @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="goCreate">创建任务</el-button>
          <el-dropdown>
            <el-button type="default">批量操作 <el-icon><arrow-down /></el-icon></el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="batchDelete">批量删除</el-dropdown-item>
                <el-dropdown-item @click="batchExport">批量导出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-card>

    <!-- 数据表格区 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @sort-change="handleSortChange"
        highlight-current-row
      >
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column type="selection" width="50" />
        <el-table-column label="任务标题" min-width="200">
          <template #default="{ row }">
            <el-link @click="showDetail(row)">{{ row.title }}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" prop="startTime" sortable width="160" />
        <el-table-column label="结束时间" prop="endTime" sortable width="160" />
        <el-table-column label="任务类型" prop="type" width="100">
          <template #default="{ row }">
            <el-tag :type="typeTag(row.type)">{{ typeLabel(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="任务规则" min-width="180">
          <template #default="{ row }">
            <el-tooltip :content="row.ruleFull" placement="top">
              <span class="ellipsis" @click="showRuleDialog(row.ruleFull)" style="cursor:pointer; color:#165dff; white-space: pre-line;">
                {{ row.ruleShort }}
                <template v-if="row.ruleFull && row.ruleFull.length > 20">...</template>
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" sortable width="160" />
        <el-table-column label="任务状态" prop="status" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTag(row.status)">{{ statusLabel(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="220">
          <template #default="{ row }">
            <el-button size="small" type="default" @click="showDetail(row)">查看</el-button>
            <el-button size="small" type="default" v-if="row.status==='draft' || row.status==='published' || row.status==='offline'" @click="editTask(row)">编辑</el-button>
            <el-button size="small" v-if="row.status==='draft'" type="success" @click="publishTask(row)">发布</el-button>
            <el-button size="small" v-if="row.status==='published'" type="warning" @click="offlineTask(row)">下架</el-button>
            <el-button size="small" v-if="row.status==='offline'" type="success" @click="republishTask(row)">重新发布</el-button>
            <el-button size="small" v-if="row.status==='draft' || row.status==='offline' || row.status==='expired'" type="danger" @click="deleteTask(row)">删除</el-button>
            <el-button size="small" type="default" v-if="row.status==='published' || row.status==='expired' || row.status==='offline'" @click="copyTask(row)">复制</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-footer">
        <div class="left">共{{ total }}条数据，当前第{{ page }}页，每页{{ pageSize }}条</div>
        <el-pagination
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page.sync="page"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 任务详情弹窗 -->
    <el-dialog v-model="showDetailDialog" :title="detailData.title" width="900px">
      <div class="detail-dialog">
        <div class="detail-left">
          <el-tag :type="typeTag(detailData.type)">{{ typeLabel(detailData.type) }}</el-tag>
          <el-tag :type="statusTag(detailData.status)" style="margin-left: 8px">{{ statusLabel(detailData.status) }}</el-tag>
          <div>开始时间：{{ detailData.startTime }}</div>
          <div>结束时间：{{ detailData.endTime }}</div>
          <div>创建时间：{{ detailData.createTime }}</div>
          <div>更新时间：{{ detailData.updateTime }}</div>
          <div>创建人：{{ detailData.creator }}</div>
        </div>
        <div class="detail-center">
          <div class="desc" v-html="detailData.desc"></div>
          <div class="rules">
            <div v-for="(rule, idx) in detailData.rules" :key="idx">
              <el-tag>{{ rule.name }}</el-tag>：{{ rule.desc }}
            </div>
          </div>
        </div>
        <div class="detail-right">
          <div>奖励类型：<el-tag>{{ rewardTypeLabel(detailData.rewardType) }}</el-tag></div>
          <div>奖励值：{{ detailData.rewardAmount }}</div>
          <div>奖励发放条件：{{ detailData.rewardCondition }}</div>
        </div>
      </div>
      <template #footer>
        <el-button type="default" @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="editTask(detailData)">编辑</el-button>
        <el-button type="default" @click="copyTask(detailData)">复制</el-button>
      </template>
    </el-dialog>

    <!-- 帮助弹窗 -->
    <el-dialog v-model="showHelp" title="操作指南" width="500px">
      <div>这里是任务管理页面的操作指南...</div>
    </el-dialog>

    <el-dialog v-model="ruleDialog.visible" title="任务规则详情" width="500px">
      <div style="white-space: pre-line; word-break: break-all;">{{ ruleDialog.content }}</div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ArrowDown } from '@element-plus/icons-vue'
import { id } from 'element-plus/es/locales.mjs'

const router = useRouter()
const search = ref({
  title: '',
  type: '',
  startTime: '',
  endTime: '',
  status: ''
})
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)
const showDetailDialog = ref(false)
const detailData = ref({})
const showHelp = ref(false)
const ruleDialog = ref({ visible: false, content: '' })

onMounted(() => {
  refreshList()
})

function goCreate() {
  router.push('/task-editor')
}
function batchDelete() {
  // 批量删除逻辑
}
function batchExport() {
  // 批量导出逻辑
}
async function refreshList() {
  loading.value = true
  try {
    const params = {
      pageSize: pageSize.value,
      pageIndex: page.value,
      orderBy: '', // 可根据排序控件赋值
      orderDirection: '', // 可根据排序控件赋值
      taskTitle: search.value.title,
      taskStatus: search.value.status,
      taskType: search.value.type,
      startTime: Array.isArray(search.value.startTime) && search.value.startTime[0] ? search.value.startTime[0] : '',
      endTime: Array.isArray(search.value.startTime) && search.value.startTime[1] ? search.value.startTime[1] : ''
    }
    
    const res = await fetch('/api/task/page', {
      method: 'POST',
      headers: { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      body: JSON.stringify(params)
    })
    const data = await res.json()
    if (data.success) {
      tableData.value = (data.data || []).map(item => {
        const ruleDesc = parseTaskRule(item.taskRule)
        return {
          id: item.id,
          title: item.taskTitle,
          cycleType: item.cycleType,
          type: item.taskType,
          claimType: item.claimType,
          startTime: item.startTime,
          endTime: item.endTime,
          status: item.taskStatus,
          createTime: item.createTime,
          ruleFull: ruleDesc,
          ruleShort: ruleDesc && ruleDesc.length > 20 ? ruleDesc.slice(0, 20) + '...' : ruleDesc
        }
      })
      total.value = data.totalCount
      page.value = data.pageIndex
      pageSize.value = data.pageSize
    } else {
      tableData.value = []
      total.value = 0
    }
  } finally {
    loading.value = false
  }
}
function doSearch() {
  page.value = 1
  refreshList()
}
function resetSearch() {
  search.value.title = ''
}
function doFilter() {
  // 筛选逻辑
}
function resetFilter() {
  search.value.type = ''
  search.value.startTime = ''
  search.value.endTime = ''
  search.value.status = ''
}
function handleSelectionChange(val) {
  // 选中项变化
}
function handleSortChange(val) {
  // 这里可根据val.prop和val.order设置params.orderBy/orderDirection
  refreshList()
}
function handlePageChange(val) {
  page.value = val
  refreshList()
}
function showDetail(row) {
  detailData.value = row
  showDetailDialog.value = true
}
function editTask(row) {
  router.push(`/task-editor?id=${row.id}`)
}
function publishTask(row) {
  // 发布任务逻辑
}
function offlineTask(row) {
  // 下架任务逻辑
}
function republishTask(row) {
  // 重新发布逻辑
}
function deleteTask(row) {
  // 删除逻辑
}
function copyTask(row) {
  // 复制逻辑
}
function exportExcel() {
  // 导出Excel逻辑
}
function exportCSV() {
  // 导出CSV逻辑
}
function typeLabel(type) {
  return { DAILY: '日常任务', TIME_LIMITED: '限时任务' }[type] || type
}
function typeTag(type) {
  return { DAILY: 'info', TIME_LIMITED: 'warning' }[type] || 'default'
}
function statusLabel(status) {
  return {
    PENDING_PUBLISH: '待发布',
    PUBLISHED: '已发布',
    DISABLED: '禁用'
  }[status] || status
}
function statusTag(status) {
  return {
    PENDING_PUBLISH: 'info',
    PUBLISHED: 'success',
    DISABLED: 'danger'
  }[status] || 'default'
}
function rewardTypeLabel(type) {
  return { point: '积分', coupon: '优惠券', cash: '现金' }[type] || type
}
function parseTaskRule(rule) {
  // 兼容字符串和对象/数组
  let arr = rule
  if (typeof rule === 'string') {
    try { arr = JSON.parse(rule) } catch { return rule }
  }
  if (!arr) return ''
  if (!Array.isArray(arr)) arr = [arr]
  // 多条规则拼接，换行分隔
  return arr.map(obj => {
    if (!obj || typeof obj !== 'object') return ''
    // 事件类型
    let eventMap = { sign: '签到', share: '分享', invite: '邀请', buy: '购买' }
    let event = eventMap[obj.eventType] || obj.eventType || ''
    // 条件
    let cond = ''
    if (obj.conditionTree && obj.conditionTree.executionFuncName === 'sign') {
      cond = `连续签到${obj.conditionTree.value}天`
    } else if (obj.conditionTree && obj.conditionTree.executionFuncName === 'invite') {
      cond = `邀请${obj.conditionTree.value}人`
    } else if (obj.conditionTree && obj.conditionTree.executionFuncName === 'share') {
      cond = `分享${(obj.conditionTree.channels||[]).join('、')}`
    } else if (obj.conditionTree && obj.conditionTree.executionFuncName === 'buy') {
      cond = `购买商品ID:${obj.conditionTree.productId||''}`
    }
    // 奖励
    let benefit = ''
    if (Array.isArray(obj.benefits) && obj.benefits.length > 0) {
      const b = obj.benefits[0]
      let rewardTypeMap = { POINT: '积分', COUPON: '优惠券', CASH: '现金' }
      benefit = `${rewardTypeMap[b.rewardType]||b.rewardType||''}${b.rewardValue?('×'+b.rewardValue):''}`
      if (b.title) benefit = b.title + (benefit ? '：' + benefit : '')
    }
    return [event, cond, benefit].filter(Boolean).join('，')
  }).filter(Boolean).join('\n')
}
function showRuleDialog(content) {
  ruleDialog.value.content = content
  ruleDialog.value.visible = true
}
</script>

<style scoped>
.task-list-page {
  padding: 0;
  background: linear-gradient(120deg, #e3e8ee 0%, #f8fafc 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.top-bar-card, .filter-bar-card, .table-card {
  margin-bottom: 18px;
  border-radius: 16px;
  box-shadow: 0 2px 16px 0 #b6c6e633;
  border: none;
  background: rgba(255,255,255,0.98);
}
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 8px 0 8px;
}
.title {
  font-size: 24px;
  font-weight: 700;
  color: #165dff;
  letter-spacing: 1px;
  text-shadow: 0 2px 8px #409eff11;
  display: flex;
  align-items: center;
  gap: 8px;
}
.actions {
  display: flex;
  gap: 10px;
}
.actions .el-button, .actions .el-dropdown {
  border-radius: 8px;
  font-weight: 500;
  font-size: 15px;
  box-shadow: 0 1px 4px #e3e8ee33;
  transition: box-shadow 0.2s;
}
.actions .el-button:hover, .actions .el-dropdown:hover {
  box-shadow: 0 2px 8px #165dff22;
}
.filter-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0 0 0;
}
.search-input {
  width: 220px;
  border-radius: 8px;
}
.filter-item {
  margin-right: 8px;
  border-radius: 8px;
}
.table-card {
  padding: 0 0 12px 0;
  border-radius: 18px;
  box-shadow: 0 4px 24px 0 #e3e8ee55;
  background: rgba(255,255,255,0.99);
}
.el-table {
  border-radius: 12px;
  overflow: hidden;
  font-size: 15px;
  background: transparent;
}
.el-table th, .el-table td {
  background: transparent !important;
}
.el-table__header th {
  background: #f4f8ff !important;
  color: #165dff;
  font-weight: 600;
  font-size: 15px;
}
.el-table__body tr:hover > td {
  background: #e6f0ff !important;
}
.table-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding: 0 12px;
}
.ellipsis {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}
.detail-dialog {
  display: flex;
  gap: 24px;
}
.detail-left, .detail-center, .detail-right {
  flex: 1;
}
.detail-center {
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  padding: 0 16px;
}
.desc {
  margin-bottom: 16px;
}
.rules {
  font-size: 14px;
  color: #555;
}
/* 任务tab美化 */
:deep(.el-tabs__item) {
  font-size: 18px !important;
  font-weight: 600 !important;
  letter-spacing: 1px;
  padding: 18px 0 18px 24px !important;
  border-radius: 10px 0 0 10px !important;
  margin-bottom: 12px !important;
  background: linear-gradient(90deg, #e3e8ee 60%, #fff 100%);
  color: #165dff !important;
  transition: background 0.2s, color 0.2s;
}
:deep(.el-tabs__item.is-active) {
  background: linear-gradient(90deg, #165dff22 60%, #fff 100%) !important;
  color: #165dff !important;
  box-shadow: 0 2px 8px #165dff22;
}
:deep(.el-tabs__item:hover) {
  background: #e0e7ef !important;
  color: #165dff !important;
}
.filter-bar-flex {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}
.filter-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}
.filter-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style> 